package cn.edu.fzu.delivery.controller;

import java.io.File;
import java.io.IOException;

import cn.edu.fzu.delivery.common.Result;
import cn.edu.fzu.delivery.exception.ServiceException;
import cn.edu.fzu.delivery.helper.UploadHelper;
import io.swagger.annotations.Api;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import com.drew.imaging.ImageMetadataReader;
import com.drew.metadata.Directory;
import com.drew.metadata.Metadata;
import com.drew.metadata.Tag;

/**
 * 上传文件
 *
 * @author fangxin
 * @date 2022/11/11
 */
@RestController
@RequestMapping("/api/upload")
@Api(tags = "文件上传服务")
public class UploadController {

    private static final Logger logger = LoggerFactory.getLogger(UploadController.class);

    @PostMapping("/image")
    public Result uploadImage(MultipartHttpServletRequest request) throws IOException {
        MultipartFile file = request.getFile("file");
        if (file == null) {
            return Result.SUCCESS;
        }
        return new Result(UploadHelper.uploadMfs(String.valueOf(System.currentTimeMillis()), file));
    }


    @PostMapping("/video")
    public Result uploadVideo(MultipartHttpServletRequest request) throws IOException {
        MultipartFile file = request.getFile("file");
        if (file == null) {
            return Result.SUCCESS;
        }
        String localFilePath = UploadHelper.uploadMfsLocal(String.valueOf(System.currentTimeMillis()), file);
        String videoType = UploadHelper.getVideoType(localFilePath);
        if (videoType == null) {
            throw new ServiceException("不支持的视频的编码格式,建议上传H264编码格式的视频！");
        }

        File localFile = new File(localFilePath);
        long fileSize = 0L;
        try {
            Metadata metadata = ImageMetadataReader.readMetadata(localFile);
            for (Directory directory : metadata.getDirectories()) {
                for (Tag tag : directory.getTags()) {
                    if ("File Size".equals(tag.getTagName())) {
                        fileSize = Long.parseLong(tag.getDescription().substring(0, tag.getDescription().indexOf(" ")));
                    }
                }
            }
        } catch (Exception e) {
            logger.error("parse video error.", e);
            throw new ServiceException("视频文件解析失败");
        }
        if (fileSize > 50 * 1024 * 1024) {
            throw new ServiceException("视频文件过大，最大仅支持50M");
        }

        return new Result(UploadHelper.transferVideoToMfs(videoType, localFilePath));
    }

}
